package com.springspirit.monitor;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.log4j.Logger;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import com.springspirit.framework.message.LogMessage;

/**
 * 응용시스템 에러메시지를 변환한다.
 * 
 * MapMessage <-> LogMessage
 * 
 * @author greatshin
 *
 */
public class MessageConvertImpl implements MessageConverter{
	
	private static Logger logger = Logger.getLogger(MessageConvertImpl.class);
	
//	private static final String LOGMESSAGE = "LogMessage";

	/**
	 *  Convert from a JMS Message to a Java object
	 */
	public Object fromMessage(Message message) throws JMSException,
			MessageConversionException {
		
		LogMessage logMessage = null;
		
		if (!(message instanceof ObjectMessage) && !(message instanceof ActiveMQTextMessage)) {
			
//			if(logger.isDebugEnabled()){
//				logger.debug("MessageConvertImpl - fromMessage : " + message.getClass().getName());
//			}
			
			throw new MessageConversionException("not javax.jms.MapMessage"); 
		} 
		
		// ActiveMQ Admin의 Send 메뉴에서 직접 메시지를 보낼 경우...(테스트용)
		if (message instanceof ActiveMQTextMessage){
			
			ActiveMQTextMessage amTextMessage = ((ActiveMQTextMessage)message);			
			logMessage = new LogMessage(amTextMessage.getText());		
			
		} 

		// 응용시스템 에러 로그 메시지
		if (message instanceof ObjectMessage) {

			ObjectMessage mapMessage = (ObjectMessage)message; 	
			logMessage = (LogMessage) mapMessage.getObject();
			
		}
		
//		if(logger.isDebugEnabled()){
//			logger.debug("[JMS] MessageConvertImpl - fromMessage: logMessage => " + logMessage.toString());
//		}
		
		return logMessage;
	}

	/*
	 * Convert a Java object to a JMS Message using the supplied session
	 * to create the message object.
	 */
	public Message toMessage(Object object, Session session) throws JMSException,
			MessageConversionException {
		if ( !(object instanceof LogMessage) ) {			 
			throw new MessageConversionException("not com.springspirit.framework.message.LogMessage"); 
		}
		
		LogMessage logMessage = (LogMessage)object; 
		
//		if(logger.isDebugEnabled()){
//			logger.debug("[JMS] MessageConvertImpl - toMessage: logMessage => " + logMessage.toString());
//		}
		
		ObjectMessage message = session.createObjectMessage(logMessage);
		return message;
	}

}
